import axios from "axios";

import {
    Notification,
    Message
} from "element-ui";
import router from "../router";

const durationTime = 3000;

const evn = localStorage.getItem("EVN")

// if (evn == "dev") {
//     axios.defaults.baseURL = "/dev-api";
// } else {
//     axios.defaults.baseURL = "/api";
// }

axios.defaults.baseURL = "http://localhost:10999";

const request = axios.create({
    timeout: 30000,
});
//
// //请求拦截器
// request.interceptors.request.use((config) => {
//
//     // 添加token
//     const token = window.sessionStorage.getItem("Authorization")
//     // console.log("【请求头token】", token)
//
//     // 是否需要token
//     const isToken = (config.header || {}).isToken === false
//     config.header = config.header || {}
//
//     if (token && !isToken) {
//         config.headers["Authorization"] = token
//     }
//
//     console.log("【请求参数】", config)
//     return config;
// });
//
//响应拦截器
request.interceptors.response.use(
    function (response) {
        console.log("【请求响应】", response)
        // 浏览器状态码
        const resStatus = response.status
        // 自定义状态码
        const resCode = response.data.code




        if (resStatus === 200 && resCode === 2002) {
            Notification({
                title: '提示',
                message: response.data.message,
                type: 'warning',
                duration: 0,
            });
        }
        //没有访问权限
        if (resStatus === 200 && resCode === 4020) {
            Message({
                message: response.data.message,
                type: 'error'
            })
        }

        // 已登录过期
        else if (resStatus === 200 && resCode === 6000 || resCode === 4010) {
            Notification.error({
                message: response.data.message,
                duration: durationTime,
            });

            router.replace("/login")
        }

        return Promise.resolve(response.data);
    },
    function (error) {
        console.log("【响应失败】", error.response)

        const errorData = error.response.data;
        const respStatus = errorData.status;

        if (respStatus === 404) {
            Notification.error({
                message: errorData.path + " " + errorData.error,
                duration: durationTime,
            });
        }

        if (respStatus && respStatus === 500) {
            Notification.error({
                message: "服务器繁忙，请联系管理员",
                duration: durationTime,
            });
        }

        return Promise.reject(error);
    }
);

export default request;